import * as wechat from "react-native-wechat";
import { Alert, DeviceEventEmitter } from "react-native";
import { toastShort } from "./ToastUtils";
import NetWorkUtil from "./NetWorkUtil";
import ApiConstants from "../common/ApiConstants";
import StorageUtil from "./StorageUtil";

function getUserInfoFormWx(res) {
  return new Promise(resolve => {
    fetch(`https://api.weixin.qq.com/sns/userinfo?access_token=${res.access_token}&openid=${res.openid}`, {
      method: "GET",
    })
      .then(response => {
        // 授权成功，获取用户头像等信息
        console.log(response);
        response.json().then(userinfo => {
          console.log(userinfo);
          resolve(userinfo);
        });
      })
      .catch(err => err.message && toastShort(err.message));
  });
}

/**
 * 微信登录 获取 token
 * @param responseCode
 */
function getAccessToken(responseCode) {
  return new Promise(resolve => {
    const appId = "wx58a330129e225f3c";
    const secret = "d3c529c7e3355dc98c6fbc049dd96d0b";
    switch (responseCode.errCode) {
      // 用户换取access_token的code，仅在ErrCode为0时有效
      case 0:
        // 获取token值
        fetch(
          `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${secret}&code=${
            responseCode.code
          }&grant_type=authorization_code`,
          { method: "GET" },
        )
          .then(response => {
            // 授权成功，获取用户头像等信息
            response.json().then(res => {
              resolve(res);
            });
          })
          .catch(err => err.message && toastShort(err.message));
        break;
      case -4:
        // 用户拒绝
        toastShort("用户拒绝");
        break;
      case -2:
        // 用户取消
        toastShort("用户取消");
        break;
      default:
        break;
    }
  });
}

function WXLogin() {
  return new Promise(resolve => {
    if (global.hasLoggedin) return;
    const scope = "snsapi_userinfo";
    const state = "wechat_sdk_demo";
    // 判断微信是否安装
    wechat.isWXAppInstalled().then(isInstalled => {
      if (isInstalled) {
        // 发送授权请求
        wechat
          .sendAuthRequest(scope, state)
          .then(responseCode => {
            // 返回code码，通过code获取access_token
            // console.log(responseCode);
            // console.log(responseCode.code);

            // StorageUtil.saveUserTest();
            // DeviceEventEmitter.emit("WEICHATLOGINSUCCESS", {});
            // toastShort("微信授权登陆成功");

            NetWorkUtil.postWithoutLogin(ApiConstants.WEICHATLOGIN, {
              code: responseCode.code,
            })
              .then(loginRes => {
                // console.log(loginRes);
                StorageUtil.saveUser(loginRes);
                resolve(loginRes);
                DeviceEventEmitter.emit("WEICHATLOGINSUCCESS", loginRes);
                toastShort("微信授权登陆成功");
              })
              .catch(loginErr => toastShort(loginErr.message));
          })
          .catch(err => {
            Alert.alert("登录授权发生错误：", err.message, [{ text: "确定" }]);
          });
      } else {
        Alert.alert("没有安装微信", "请先安装微信客户端在进行登录", [{ text: "确定" }]);
      }
    });
  });
}

module.exports = {
  WXLogin,
};
